package com.choudou5.solr.service;

import cn.hutool.core.collection.CollUtil;
import com.choudou5.solr.annotation.ServiceInfo;
import com.choudou5.solr.bean.SolrElevateBean;
import com.choudou5.solr.util.cache.CacheFactory;
import com.choudou5.solr.util.cache.impl.LFUCache;

import java.util.List;
import java.util.Map;

/**
 * @name 竞价排名 接口
 * @author choudou5
 * @date 2018-7-21
 */
@ServiceInfo(table = "solr_elevate", desc = "竞价排名")
public class SolrElevateService extends BaseService<SolrElevateBean> {

    private static final LFUCache<String, List<String>> CACHE_MAP = CacheFactory.newLFUCache(500, 300 * 1000); //5分钟有效期


    public void save(String module, String keyword, Map<String, String> map){
        int top = 1;
        for (String docId : map.keySet()) {
            String cacheKey = module+"_"+keyword;
            CACHE_MAP.get(cacheKey);
            SolrElevateBean bean = new SolrElevateBean(module, keyword, docId, map.get(docId), top);
            add(bean);
            top++;
        }
    }

    public void save(String module, String keyword, String docId){
        int top = 1;
        String cacheKey = module+"_"+keyword;
        CACHE_MAP.get(cacheKey);
        SolrElevateBean bean = new SolrElevateBean(module, keyword, docId, null, top);
        add(bean);
    }

    public List<String> findCache(String module, String keyword){
        String cacheKey = module+"_"+keyword;
        List<String> list = CACHE_MAP.get(cacheKey);
        if(CollUtil.isEmpty(list)){
            list = findOneColumnList(String.class, "doc_id", "module = '" + module + "' AND keyword = '" + keyword + "' ORDER BY top ASC ");
            CACHE_MAP.put(cacheKey, list);
        }
        return list;
    }

}
